package queue;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;

//347. 前 K 个高频元素
public class Num347_topKFrequent {
    private class Freq implements Comparable<Freq>{
        private  int key;
        private int times;//出现的次数

        public Freq(int key, int times) {
            this.key = key;
            this.times = times;
        }

        @Override
        public int compareTo(Freq o) {
            return o.times - this.times;
        }
    }
    public int[] topKFrequent(int[] nums, int k) {
        Queue<Freq> queue = new PriorityQueue<>();
        Map<Integer , Integer> map = new HashMap<>();
        int ret [] = new int[k];
        for (int i : nums){
            map.put(i , map.getOrDefault(i , 0) + 1);
        }
        for (Map.Entry<Integer , Integer> entry : map.entrySet()){
            //遍历map
            queue.offer(new Freq(entry.getKey() , entry.getValue()));
        }
        for (int i = 0; i < k; i++) {
            ret[i] = queue.poll().key;
        }
        return ret;




    }

}
